
// webSocketServer  服务器文件

let ws = require('ws');  //webSocket
const webSocketServer = ws.Server;
const port = 3900;

// 1.创建服务器--绑定ip  端口监听端口
let wss = new webSocketServer({port});
console.log(`webSocketServer is running at ws://0.0.0.0:${port}`);

let info = 'nz1903_';
let count = 0;
let clientUserMap = {};  //存放多个客户端

// 2.监听客户端的连接
wss.on('connection',(socket)=>{ // 表示客户端连接成功 socket表示客户端的连接对象
    count++;
    socket.name = info+count;
    clientUserMap[socket.name] = socket; //存放连接服务器成功的客户端
    console.log(`客户端上线。。。。`);

    // 3.监听客户端发来的消息，并将其转发给其他客户
    socket.on('message',(msg)=>{
        // console.log(msg);
        // 将消息广播出去
        boradcast(socket,msg);
    });
    // 4.监听客户端的关闭
    socket.on('close',()=>{
        boradcast(socket,'我已经下线');
        // 删除对象
        delete clientUserMap[socket.name];
    });
})

// 将消息广播出去
function boradcast(socket,msg){
    for(var i in clientUserMap){  //遍历客户端对象
        let h = new Date().getHours();
        let m = new Date().getMinutes();
        //谁 说 msg
        clientUserMap[i].send(`${socket.name}说：(${h}:${m}) ${msg}`);
    }
}


















